package com.ruike.alisurface.ui.payPage;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.SystemClock;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ruike.alisurface.MyApplication;
import com.ruike.alisurface.R;
import com.ruike.alisurface.Serials.MsgEventBus;
import com.ruike.alisurface.base.BaseAty;
import com.ruike.alisurface.bean.CarGoodsBeans;
import com.ruike.alisurface.bean.CardTopUpBean;
import com.ruike.alisurface.bean.OrderrBean;
import com.ruike.alisurface.bean.ShopDetailBean;
import com.ruike.alisurface.http.MchApiHttp;
import com.ruike.alisurface.http.OtherHttp;
import com.ruike.alisurface.ui.dialog.CustomDialog;
import com.ruike.alisurface.utils.BackMainUtils;
import com.ruike.alisurface.utils.ShareKey;
import com.ruike.alisurface.utils.ZXingUtils;
import com.voodoo.lib_utils.GsonUtils;
import com.voodoo.lib_utils.L;
import com.voodoo.lib_utils.ShareUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Author: voodoo
 * CreateDate: 2020-04-08
 * Description: 扫码页
 */
public class PayForPointActivity extends BaseAty {

    @BindView(R.id.alchat_zxing_count_time)
    TextView countTimeTv;
    @BindView(R.id.alchat_zxing_code)
    ImageView qRCodeIv;
    @BindView(R.id.qrcode_showPayApp_ll)
    LinearLayout showPayAppLl;
    @BindView(R.id.alchat_zxing_price)
    TextView priceTv;

    private List<CarGoodsBeans> shoppingCardList;
    private ShopDetailBean shopDetailBean;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_pay_wealchat;
    }

    @Override
    protected void initViews() {
        L.i("积分支付页==" + this.getClass().getName());
        initTitleBar(false);
    }

    @Override
    protected void initData() {
        showPayAppLl.setVisibility(View.GONE);
        shoppingCardList = MyApplication.finalDbUtils.findAll(CarGoodsBeans.class);
        SystemClock.sleep(500);
        if (shoppingCardList == null) {
            L.i("查询商品数据异常");
            showErrorTip("查询商品数据异常");
            startCountdownTimer(3, null, SelectPayTypeActivity.class);
            return;
        }
        createOrder();
    }

    private void createOrder() {
        showProgressDialog("正在生成二维码加载数据，请稍后......", false);
        if (ShareUtils.getInstance().getInt(ShareKey.IS_SHOP_TYPE, 1) == 1) {
            L.i("按货道展示上传信息");
        } else {
            L.i("按商品类型展示上传信息");
        }
        OtherHttp.createOrder(shoppingCardList, this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        startCountdownTimer(300, countTimeTv, isFace ? null : SelectPayTypeActivity.class);
    }

    @Override
    public void onSuccess(String requestUrl, String requestJsonStr) {
        super.onSuccess(requestUrl, requestJsonStr);
        if (OtherHttp.CREATE_ORDER_BY_PRODUCT_URL.equals(requestUrl) || OtherHttp.CREATE_ORDER_BY_SLOT_URL.equals(requestUrl)) {

            String orderId = "";
            double totalPoint = 0;
            double payFee = 0;
            String url = "";

            try {
                JSONObject jsonObject = new JSONObject(requestJsonStr);
                JSONObject jsonData = jsonObject.optJSONObject("data");
                if (jsonData == null) {
                    showErrorTip("接口返回的订单JSON异常");
                    startCountdownTimer(3, null, null);
                    return;
                }
                orderId = jsonData.optString("order_id");
                totalPoint = jsonData.optDouble("total_point");
                payFee = jsonData.optDouble("pay_fee");
                url = jsonData.optString("url");
                JSONArray orderDetails = jsonData.optJSONArray("detail_list");

                if (orderDetails == null) {
                    showErrorTip("接口返回的订单出货详情异常");
                    startCountdownTimer(3, null, null);
                    return;
                }

                shopDetailBean = new ShopDetailBean(orderId);
                shopDetailBean.setPromotion_fee(0);
                shopDetailBean.setTotal_fee(totalPoint);
                shopDetailBean.setPay_fee(totalPoint);
                L.i("shopDetailBean", shopDetailBean.toString());

                List<ShopDetailBean.OrderDetailsBean> orderDetailsBeanList = new ArrayList<>();
                for (int i = 0; i < orderDetails.length(); i++) {
                    JSONObject detailJson = (JSONObject) orderDetails.get(i);

                    ShopDetailBean.OrderDetailsBean orderDetailsBean = new ShopDetailBean.OrderDetailsBean();
                    orderDetailsBean.setSlotIndex(detailJson.getInt("slotIndex"));
                    orderDetailsBean.setQuantity(detailJson.getInt("quantity"));
                    orderDetailsBean.setSlotTypeId(detailJson.getInt("slotType"));

                    orderDetailsBeanList.add(orderDetailsBean);
                }
                shopDetailBean.setDetailOrderList(orderDetailsBeanList);

            } catch (JSONException e) {
                e.printStackTrace();
            }

            qRCodeIv.setImageBitmap(ZXingUtils.getInstance().createQRImage(url, 500, 500, BitmapFactory.decodeResource(getResources(), 0)));
            priceTv.setText(String.format(Locale.ENGLISH, "总积分：%.2f", totalPoint));

            startCountdownTimer(120, countTimeTv, SelectPayTypeActivity.class);

            // 开始轮询
            startTimer();

        } else if (requestUrl.endsWith("getPayResult")) {
            JSONObject object = null;
            try {
                object = new JSONObject(requestJsonStr);
                int code = object.optInt("code");
                L.i("getPayResult==" + requestJsonStr);
                if (code == 0) {
                    String order_code = ShareUtils.getInstance().getString(ShareKey.ORDER_RESULT, "");
                    L.iTag("支付页==order_code= ", "上次的单号==" + order_code + "==");
                    if (!TextUtils.isEmpty(order_code) && shopDetailBean != null && order_code.equals(shopDetailBean.getOrderId())) {
                        L.iTag("支付页==order_code= ", "这次的单号=="
                                + shopDetailBean.getOrderId() + "==" + "多次出 货，订单号已经出货过 无法再次出货 回到主页面");
                        BackMainUtils.setActivity(this);
                        finish();
                        return;
                    }
                    Bundle bundle = new Bundle();
                    bundle.putString("pay_type", "point");
                    bundle.putSerializable("orderBeanData", shopDetailBean);
                    startActivity(PayShowShopActivity.class, bundle);
                    finish();
                } else {
                    L.i("getPayResult" + "==等待支付=");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onError(String requestUrl, String errorMsg) {
        super.onError(requestUrl, errorMsg);
        if (requestUrl.endsWith("getPayResult")) {
            L.e(requestUrl + "==onError=" + errorMsg, "---等待支付--");
            // 开始轮询
            startTimer();
        } else if (OtherHttp.CREATE_ORDER_BY_PRODUCT_URL.equals(requestUrl) || OtherHttp.CREATE_ORDER_BY_SLOT_URL.equals(requestUrl)) {
            L.e(requestUrl + "=onError==" + errorMsg);
            showErrorTip(errorMsg);
            startCountdownTimer(3, null, SelectPayTypeActivity.class);
        }
    }

    Timer timer;
    TimerTask timerTask;

    void startTimer() {
        cancelTimer();
        timer = new Timer();
        timerTask = new TimerTask() {
            @Override
            public void run() {
                MchApiHttp.getPayResult(PayForPointActivity.this, shopDetailBean.getOrderId());
            }
        };
        timer.schedule(timerTask, 3000);
    }

    void cancelTimer() {
        if (timer != null) {
            timer.cancel();
            timer.purge();
            timer = null;
        }
        if (timerTask != null) {
            timerTask.cancel();
            timerTask = null;
        }
    }

    @OnClick({R.id.alchatPay_goback_imgv})
    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.alchatPay_goback_imgv:
                String tip = "支付过程中请勿关闭该扫码支付页面，否则即使支付成功也无法出货！！！\r\n\r\n" +
                        "如想返回其它页面则点击确认，否则点击取消等待支付完成后出货！！！";
                gobackTip(tip);
                break;
        }
    }

    CustomDialog dialog;

    public void gobackTip(String tip) {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
        dialog = new CustomDialog.Builder(this).setTitle("温馨提示")
                .setMessage(tip).setTouchOutsideCloseDialog(false)
                .setPositiveButton("确认", (dialog, which) -> {
                    sendOrderStatus(0);
                    startCountdownTimer(0, null, isFace ? null : SelectPayTypeActivity.class);
                }).setNegativeButton("取消", null).create();
        dialog.show();
    }

    @Override
    public void doEventBusResult(MsgEventBus event) {
        if (event.getType().equals("计时结束") && event.getMessage().equals("查询订单倒计时结束")) {
            sendOrderStatus(1);
        }
    }

    boolean is_sign_order_state = false;

    /**
     * 上传订单是否超时
     */
    public void sendOrderStatus(int sign_order_state) {
        if (!TextUtils.isEmpty(shopDetailBean.getOrderId()) && !is_sign_order_state) {
            is_sign_order_state = true;
            MchApiHttp.sendSign_order(shopDetailBean.getOrderId(), sign_order_state, PayForPointActivity.this);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        L.i("==onDestroy==");
        if (dialog != null && dialog.isShowing()) {
            dialog.cancel();
            dialog = null;
        }
        MchApiHttp.cancalpayResult();
        cancelTimer();
        if (dialog != null) {
            dialog.dismiss();
            dialog = null;
        }
    }


}
